package ui

import (
	"lnzw/common/proto/cs_gen"
	"lnzw/engine/log"
	"lnzw/server/test/test_fyne/test_3/data"
	"lnzw/server/test/test_fyne/test_3/transport"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/canvas"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/dialog"
	"fyne.io/fyne/v2/theme"
	"fyne.io/fyne/v2/widget"
	"go.uber.org/zap"
)

type LoginUI struct {
	IUIBase
	content *dialog.CustomDialog
}

func NewLoginUI(parentUI IUIBase) *LoginUI {
	ui := &LoginUI{
		IUIBase: parentUI,
	}
	return ui
}

func (m *LoginUI) Init() {
	if m.content != nil {
		m.content.Show()
		return
	}
	c := container.NewWithoutLayout()
	namelabel := widget.NewLabel("用户名:")
	namelabel.Alignment = fyne.TextAlignTrailing
	namelabel.Resize(fyne.NewSize(30, 20))
	namelabel.Move(fyne.NewPos(30, 10))
	nameEntry := widget.NewEntry()
	nameEntry.Resize(fyne.NewSize(140, 38))
	nameEntry.Move(fyne.NewPos(70, 10))
	pwdlabel := widget.NewLabel("密码:")
	pwdlabel.Alignment = fyne.TextAlignTrailing
	pwdlabel.Resize(fyne.NewSize(30, 20))
	pwdlabel.Move(fyne.NewPos(30, 55))
	pwdEntry := widget.NewEntry()
	pwdEntry.Resize(fyne.NewSize(140, 38))
	pwdEntry.Password = true
	pwdEntry.Move(fyne.NewPos(70, 55))
	c.Add(namelabel)
	c.Add(nameEntry)
	c.Add(pwdlabel)
	c.Add(pwdEntry)
	customd := dialog.NewCustomWithoutButtons("", c, m.GetWindow())
	customd.Resize(fyne.NewSize(295, 240))
	btnLogin := widget.NewButton("  登录  ", func() {
		rsp, err := transport.DefaultSyncSendWithRsp("", data.LoginCatalog, &cs_gen.ReqLogin{Account: nameEntry.Text, Password: pwdEntry.Text})
		if err != nil {
			log.Error("send failed", zap.Error(err))
			return
		}
		rspLogin := rsp.(*cs_gen.ResLogin)
		GlobalEventMgr.Dispatch(EventType_Login, rspLogin)
	})
	btnExit := widget.NewButton("  退出  ", func() {
		m.GetWindow().Close()
	})
	sep := widget.NewSeparator()
	sepContainer := container.NewWithoutLayout(
		canvas.NewRectangle(theme.Color(theme.ColorNamePrimary)), // 设置背景颜色
		sep,
	)

	customd.SetButtons([]fyne.CanvasObject{btnLogin, sepContainer, btnExit})
	customd.Show()
	m.content = customd
}

func (m *LoginUI) Close() {
	if m.content != nil {
		m.content.Hide()
	}
}
